import axios from 'axios';
import router from './router';
import { AppStore } from '@/stores/store';
import { IsEmpty } from './utils/common';

// Axios.defaults.baseURL = import.meta.env.RENDERER_VITE_SERVER_URL;

const Axios = axios.create();
Axios.defaults.baseURL = (window as any).apiUrl.VITE_SERVER_URL;
Axios.defaults.timeout = 60000;

// 添加一个请求拦截器
Axios.interceptors.request.use(
  function (config) {
      console.log('请求开始：', config)
    let store = AppStore();

      if (!config.url.includes('organizeLis')){
          if (config.method == "post") {
              if (config.data) {
                  config.data.orgId = store.userInfo.orgId;
              }
          } else if (config.method == "get") {
              if (config.params) {
                  if (IsEmpty(config.params.orgId)) {
                      config.params.orgId = store.userInfo.orgId;
                  }
              }
          }
      }
    // Do something before request is sent
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = 'Bearer ' + token;
    }
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 添加一个响应拦截器
Axios.interceptors.response.use(
  function (response) {
    //如果是导出的Excel数据，直接返回二进制Data
    if (response.headers['content-type'] === 'application/vnd.openxmlformats' || response.headers['content-type'] === 'application/vnd.ms-excel' || response.data.exportId) {
      return response.data;
    }
    //token错误，重新登录
    if (response.data.status.code === 402) {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      setTimeout(function () {
        router.push('/login');
      }, 1000);
    }

    //token过期--获取更新的token
    const newtoken = response.headers.newtoken;
    //token过期--如果token存在则存在localStorage
    if (newtoken) {
      console.log('token过期，已重新赋值');
      localStorage.setItem('token', newtoken);
    }

    if (response.data && response.data.status && response.data.status.msg && response.data.status.msg.lastIndexOf('java.lang.RuntimeException: java.lang.RuntimeException:') > -1) {
      response.data.status.msg = response.data.status.msg.replace('java.lang.RuntimeException: java.lang.RuntimeException:', '');
    }
    return response.data;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

export default Axios;
